import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject, Subscription, timer } from 'rxjs';
import { filter, tap } from 'rxjs/operators';

enum Action {
  START = 'start',
  STOP = 'stop',
  RESET = 'reset',
}

@Component({
  selector: 'app-counter',
  templateUrl: './counter.component.html',
  styleUrls: ['./counter.component.scss']
})
export class CounterComponent implements OnInit, OnDestroy {

  startBtn = '开始';
  stopBtn = '暂停';
  resetBtn = '重置';

  l = 2;
  mult = Math.pow(10, this.l);
  timer$ = timer(0, 1000/this.mult);
  timerSubscription!: Subscription;

  countSubject$: Subject<Action> = new Subject();
  countSubscription!: Subscription;

  count = 0;
  get countStr(): string {
    return this.count.toFixed(this.l);
  }

  get isRunning(): boolean {
    return this.timerSubscription && !this.timerSubscription.closed;
  }

  private add(num: number, n = 1) {
    return (num * this.mult + n) / this.mult;
  }

  constructor() { }

  ngOnInit(): void {
    this.countSubscription = this.countSubject$.pipe(
      tap(action => {
        console.log('action', action);
        if (action === Action.RESET) {
          this.count = 0;
        }
      }),
      filter(action => {
        if (action === Action.START) {
          return true;
        }
        this.timerSubscription?.unsubscribe();
        return false;
      }),
      tap(() => {
        console.log(this.timerSubscription);
        if (!this.isRunning) {
          this.timerSubscription = this.timer$.pipe(
            tap(() => {
              this.count = this.add(this.count);
            })
          ).subscribe();
        }
      })
    ).subscribe();
  }

  start(): void {
    this.countSubject$.next(Action.START);
  }

  stop(): void {
    this.countSubject$.next(Action.STOP);
  }

  reset(): void {
    this.countSubject$.next(Action.RESET);
  }

  ngOnDestroy(): void {
    this.countSubscription?.unsubscribe();
  }

}
